import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
// import {ExclamationCircleOutlined} from '@ant-design/icons'

export interface RequestOptions {
  /** 当前接口权限, 不需要鉴权的接口请忽略， 格式：sys:user:add */
  permCode?: string;
  /** 是否直接获取data，而忽略message等 */
  isGetDataDirectly?: boolean;
  /** 请求成功是提示信息 */
  successMsg?: string;
  /** 请求失败是提示信息 */
  errorMsg?: string;
  /** 是否mock数据请求 */
  isMock?: boolean;
}

const UNKNOWN_ERROR = '未知错误，请重试';
// 是否生产环境

const baseApiUrl = "";
/** mock请求路径前缀 */
const service = axios.create({
  // baseURL: baseApiUrl,
  timeout: 6000,
});

service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 200) {
      

      // Illegal token
      if (res.code === 11001 || res.code === 11002) {
        window.localStorage.clear();
        window.location.reload();
      }

      // throw other
      const error = new Error(res.message || UNKNOWN_ERROR) as Error & { code: any };
      error.code = res.code;
      return Promise.reject(error);
    } else {
      return res;
    }
  },
  (error) => {
    // 处理 422 或者 500 的错误异常提示
    const errMsg = error?.response?.data?.message ?? UNKNOWN_ERROR;
    error.message = errMsg;
    return Promise.reject(error);
  },
);

export type Response<T = any> = {
  code: number;
  message: string;
  data: T;
};

export type BaseResponse<T = any> = Promise<Response<T>>;

/**
 *
 * @param method - request methods
 * @param url - request url
 * @param data - request data or params
 */
export const request = async <T = any>(
  config: AxiosRequestConfig,
): Promise<T> => {
  try {
    const fullUrl = `${(baseApiUrl) + config.url}`;
    if (!config.url?.startsWith('project-')) {
      config.url = fullUrl.replace(/(?<!:)\/{2,}/g, '/');
    } else {
      config.url = `${baseApiUrl}/${config.url}`;
    }
    return service.request(config);
  } catch (error: any) {
    return Promise.reject(error);
  }
};
